<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2023 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\api\controller;

use app\api\validate\WechatLogin as WechatLoginValidate;
use think\facade\Db;
use app\common\service\wechat\WeChatMnpService;
use app\api\service\UserService;
use app\common\enum\UserEnum;
use app\common\model\User as UserModel;

class Login extends BaseApi
{

    public function mnpLogin()
    {
        $params = (new WechatLoginValidate())->post()->goCheck('mnpLogin');

        Db::startTrans();
        try {
            //通过code获取微信 openid
            $response = (new WeChatMnpService())->getMnpResByCode($params['code']);

            $userServer = new UserService($response, UserEnum::WECHAT_MMP);
            $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();

            //计算用户等级
            $userInfo['level'] = $userServer::userLevel($userInfo['exp']);

            // 更新登录信息
            self::updateLoginInfo($userInfo['id']);

            Db::commit();
            return $this->data($userInfo);
        } catch (\Exception  $e) {
            Db::rollback();
            return $this->fail($e->getMessage());
        }
    }

    /**
     * @notes 更新登录信息
     * @param $userId
     * @throws \Exception
     * @author 段誉
     * @date 2022/9/20 19:46
     */
    public static function updateLoginInfo($userId)
    {
        $user = UserModel::findOrEmpty($userId);
        if ($user->isEmpty()) {
            throw new \Exception('用户不存在');
        }

        $time = time();
        $user->login_time = $time;
        $user->login_ip = request()->ip();
        $user->update_time = $time;
        $user->save();
    }

    /**
     * 获取scheme码,用于H5登录时拉取微信小程序
     * @return void
     */
    public function generateScheme()
    {
        $scheme = (new WeChatMnpService())->generateScheme('/pages/user/auth');

        return $this->data(json_decode($scheme)->openlink);
    }

    /**
     * Scheme码登录
     */
    public function schemeLogin()
    {
        $scheme = input('scheme');
        $info = (new WeChatMnpService())->queryscheme($scheme);
        $info = json_decode($info);

        $openid = $info->visit_openid;

        if (empty($openid)) {
            return $this->fail("等待用户跳转小程序授权", 0);
        }

        Db::startTrans();
        try {

            $response = [
                "openid" => $openid
            ];

            $userServer = new UserService($response, UserEnum::WECHAT_MMP);
            $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();

            //计算用户等级
            $userInfo['level'] = $userServer::userLevel($userInfo['exp']);

            // 更新登录信息
            self::updateLoginInfo($userInfo['id']);

            Db::commit();
            return $this->data($userInfo);
        } catch (\Exception  $e) {
            Db::rollback();
            return $this->fail($e->getMessage());
        }
    }
}